package com.chenyun.tenant;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.chenyun.common.vo.ApplicationProperties;
import com.chenyun.tenant.aop.TenantIgnoreAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * TenantAutoConfiguration：
 * Description:
 *
 * @author: Lonni
 * @date: 2024/5/21 0021 14:59
 */
@ConditionalOnProperty(value = "chenyun.tenantEnable",havingValue = "true")
@Configuration
@Slf4j
@Import(TenantIgnoreAspect.class)
public class TenantAutoConfiguration implements Serializable {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Bean
    public TenantLineInnerInterceptor tenantHandler(@Autowired MybatisPlusInterceptor interceptor){
        log.info("开始添加多租户插件------->");
        TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(new TenantHandlerImpl(applicationProperties));
        //返回的是一个只读列表
        List<InnerInterceptor> interceptors = interceptor.getInterceptors();
        List<InnerInterceptor> innerInterceptorList=new ArrayList<>(interceptors.size()+1);
        //多租户插件需要添加到第一个
        innerInterceptorList.add(tenantLineInnerInterceptor);
        innerInterceptorList.addAll(interceptors);
        interceptor.setInterceptors(innerInterceptorList);
        log.info("添加多租户插件完成------->");
        return tenantLineInnerInterceptor;
    }


}



